package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.hash.Hash;
import cn.hutool.db.handler.HandleHelper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 消费者线程池，用来开启线程去读取消息队列的
     */
    public static final ExecutorService HANDLE_MESSAGE_POOL = Executors.newSingleThreadExecutor();

    /**
     * 消息队列的名称
     */
    public static final String QUEUE_NAME = "stream.orders";
    /**
     * 消费者组的名称
     */
    public static final String GROUP_NAME = "g1";
    /**
     * 消费者的名称
     */
    public static final String CONSUMER_NAME = "c1";

    /**
     * 当前类的代理对象
     */
    @Resource
    private IVoucherOrderService proxy;

    @PostConstruct
    public void listeningMQ() {
        // 提前创建消费者组
        try {
            stringRedisTemplate.opsForStream().createGroup(QUEUE_NAME, ReadOffset.from("0"), GROUP_NAME);
        } catch (Exception e) {
            log.info("消费者组已存在");
        }
        HANDLE_MESSAGE_POOL.submit(new MessageHandler());
    }

    private class MessageHandler implements Runnable {

        @Override
        public void run() {
            // 开机前先去看看pending-list里面有没有消息
            this.handleException();

            while (true) {
                // 1. 从消息队列里面读取消息
                // xreadgroup group g1 c1 count 1 block 2000 stream.orders >
                List<MapRecord<String, Object, Object>> messagesList = stringRedisTemplate.opsForStream().read(
                        Consumer.from(GROUP_NAME, CONSUMER_NAME),
                        StreamReadOptions.empty().count(1).block(Duration.ZERO),
                        StreamOffset.create(QUEUE_NAME, ReadOffset.lastConsumed())
                );
                // 2. 如果读取失败，则continue
                if (CollectionUtils.isEmpty(messagesList)) {
                    log.info("没有最新消息");
                    continue;
                }
                try {
                    // 3. 读取成功，数据转换
                    MapRecord<String, Object, Object> messageMap = messagesList.get(0);
                    RecordId messageId = messageMap.getId();
                    // 订单的信息
                    Map<Object, Object> message = messageMap.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(message, new VoucherOrder(), true);
                    // 4. 创建订单
                    handleOrder(voucherOrder);
                    // 5. 如果创建成功那么则去发ack
                    stringRedisTemplate.opsForStream().acknowledge(QUEUE_NAME, GROUP_NAME, messageId);
                } catch (Exception e) {
                    log.error("创建订单失败");
                    // 去pending-list里面把
                    handleException();
                }
            }
        }

        private void handleException() {
            while (true) {
                try {
                    // 1. 从pending-list里面读取消息
                    // list中获取订单信息 xreadgroup group g1 c1 count 1 BLOCK stream.orders 0
                    List<MapRecord<String, Object, Object>> messagesList = stringRedisTemplate.opsForStream().read(
                            Consumer.from(GROUP_NAME, CONSUMER_NAME),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(QUEUE_NAME, ReadOffset.from("0"))
                    );
                    // 2. 如果pending-list里面没有消息那么直接结束
                    if (CollectionUtils.isEmpty(messagesList)) {
                        break;
                    }
                    // 3. 读取成功，数据转换
                    MapRecord<String, Object, Object> messageMap = messagesList.get(0);
                    RecordId messageId = messageMap.getId();
                    // 订单的信息
                    Map<Object, Object> message = messageMap.getValue();
                    log.error("消息是{}", message);
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(message, new VoucherOrder(), true);
                    // 4. 创建订单
                    handleOrder(voucherOrder);
                    // 5. 如果创建成功那么则去发ack
                    stringRedisTemplate.opsForStream().acknowledge(QUEUE_NAME, GROUP_NAME, messageId);
                } catch (Exception e) {
                    log.error("pending-list里面消费失败{}", e);
                    // 发送异常，继续在pending-list里面读
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }

        /**
         * 假如我们是多线程消费，那么还是会出现线程安全的问题，所以要加锁
         * 其实本地的锁就可以
         *
         * @param voucherOrder
         */
        private void handleOrder(VoucherOrder voucherOrder) {
            // 1. 获取用户id
            Long userId = voucherOrder.getUserId();
            // 2. 创建锁
            ILock myLock = new MyLock(RedisConstants.LOCK_ORDER_KEY + userId, stringRedisTemplate);
            boolean isLock = myLock.tryLock();
            // 加锁失败就意味着有人刷单，因为我们的锁的key是userId
            if (!isLock) {
                return;
            }
            // 如果同一个用户刷单，那么下面只有一个线程能走到这里
            try {
                proxy.createOrder(voucherOrder);
            } finally {
                myLock.unlock();
            }
        }
    }


    /**
     * 库存预检和一人一单判断的Lua脚本
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        // Lua脚本的位置
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill2.lua"));
        // Lua脚本返回的类型
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    @Override
    public long seckillVoucher(Long voucherId) {
        // 1. 获取用户
        Long userId = UserHolder.getUser().getId();
        // 2. 调用lua脚本判断是否有购买资格
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        // Lua + redis 是原子性的不会出现线程安全的问题
        if (result == null) {
            throw new RuntimeException("系统异常");
        }
        if (result == 1L) {
            throw new RuntimeException("库存不足");
        }
        if (result == 2L) {
            throw new RuntimeException("不可重复下单");
        }
        if (result == 3L) {
            throw new RuntimeException("活动尚未开始");
        }
        if (result == 4L) {
            throw new RuntimeException("活动已结束");
        }

        long orderId = redisIdWorker.nextId("order");
        Map<String, String> message = new HashMap<>();
        message.put("id", String.valueOf(orderId));
        message.put("userId", String.valueOf(userId));
        message.put("voucherId", String.valueOf(voucherId));

        // 消息未成功到达消息队列，就让他一直发
        int count = 0;
        while (count < 2) {
            String messageId = stringRedisTemplate.opsForStream().add(QUEUE_NAME, message).getValue();
            if (StringUtils.isNotBlank(messageId)) {
                break;
            }
            log.error("订单：{} 消息未成功发送给消息队列，重试{}", orderId, count);
            count++;
        }
        // 3.返回订单id
        return orderId;
    }

    /**
     * 因为这里需要删减库存和创建订单是原子性的操作，所以加了事务
     *
     * @param voucherOrder 订单
     * @return
     */
    @Transactional
    public void createOrder(VoucherOrder voucherOrder) {

        Long voucherId = voucherOrder.getVoucherId();
        Long userId = voucherOrder.getUserId();
        // 查订单
        LambdaQueryWrapper<VoucherOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VoucherOrder::getUserId, userId);
        queryWrapper.eq(VoucherOrder::getVoucherId, voucherId);
        int count = count(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("不可重复下单！");
        }
        //5，扣减库存
        LambdaUpdateWrapper<SeckillVoucher> updateWrapper = new LambdaUpdateWrapper<>();
        // set stock = stock - 1 where voucherId = voucherId and stock > 0
        updateWrapper.eq(SeckillVoucher::getVoucherId, voucherId);
        updateWrapper.gt(SeckillVoucher::getStock, 0);
        updateWrapper.setSql("stock = stock - 1");
        boolean success = seckillVoucherService.update(updateWrapper);
        if (!success) {
            //扣减库存
            throw new RuntimeException("库存不足！" + voucherId);
        }
        save(voucherOrder);
    }


    /**
     * 秒杀未优化前的代码
     * @param voucherId
     * @return
     */
//    @Override
//    public long seckillVoucher(Long voucherId) {
//        // 1.查询优惠券
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        // 2.判断秒杀是否开始
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            // 尚未开始
//            throw new RuntimeException("秒杀尚未开始！");
//        }
//        // 3.判断秒杀是否已经结束
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            // 尚未开始
//            throw new RuntimeException("秒杀已经结束！");
//        }
//        // 4.判断库存是否充足，这里会发生线程安全问题
//        // 假设库存只有1个，然后这里有100个线程进行判断，都发现库存大于1
//        if (voucher.getStock() < 1) {
//            // 库存不足
//            throw new RuntimeException("库存不足！");
//        }
//        // 5. 一人一单判断，这里会发送线程安全问题
//        Long userId = UserHolder.getUser().getId();
//
//        // 通过互斥锁，让这是userId相同的线程在下面串行执行
//        // 这个是Redisson实现的
//        //RLock myLock = redissonClient.getLock("locK:order:" + userId);
//        ILock myLock = new MyLock(RedisConstants.LOCK_ORDER_KEY + userId, stringRedisTemplate);
//        boolean isLock = myLock.tryLock();
//        // 加锁失败就意味着有人刷单，因为我们的锁的key是userId
//        if (!isLock) {
//            throw new RuntimeException("不可重复下单！");
//        }
//        // 如果同一个用户刷单，那么下面只有一个线程能走到这里
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createOrder(voucherId);
//        } finally {
//            myLock.unlock();
//        }
//    }
}
